package com.ag.zlw.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ag.zlw.dao.TbRoleDAO;
import com.ag.bean.TbRole;
import com.ag.common.AgException;
import com.ag.common.IBaseService;
import com.ag.common.IDUtil;


@Service("RoleService")
public class RoleServiceImpl implements IBaseService<TbRole, String> {

	private static final Logger logger = Logger
			.getLogger(RoleServiceImpl.class);

	@Resource(name = "ZLWTbRoleDAO")
	private TbRoleDAO roleDAO;

	/**
	 * 根据角色ID删除角色
	 */
	@Override
	public boolean delete(String id) {
		try {
			TbRole role = roleDAO.findById(id);
			role.setA(IDUtil.DELETE);
			roleDAO.attachDirty(role);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AgException("删除角色失败！", e);
		}
	}

	@Override
	public boolean delete(TbRole t) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean update(TbRole t) {
		// TODO Auto-generated method stub
		return false;
	}

	public List<TbRole> findAllRole() {
		// return this.roleDAO.findAll();
		String hsql = "select r from TbRole r where r.a = ?";
		return roleDAO.find(hsql, IDUtil.PRESERVE);
	}

	@Override
	public TbRole findById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 保存角色
	 */
	@Override
	public boolean save(TbRole t) {
		String hsql = "select count(*) from TbRole r where r.RName = '"
				+ t.getRName() + "'";
		long cnt = (Long) roleDAO.find(hsql).get(0);
		if (cnt == 0) {
			try {
				roleDAO.save(t);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			String str = "select count(*) from TbRole r where r.RName = '"
					+ t.getRName() + "' and r.a = " + IDUtil.DELETE;
			long cnt1 = (Long) roleDAO.find(hsql).get(0);
			if (cnt1 != 0) {
				TbRole role = roleDAO.findByRName(t.getRName()).get(0);
				role.setA(IDUtil.PRESERVE);
				roleDAO.attachDirty(role);
				return true;
			}
		}
		return false;
	}
}
